Description:
Unlike Java(tm), C# does not allow you to specify the list of exceptions
that can be thrown by a method.
It simplifies programming but does not make it possible for the compiler to
detect unhandled exceptions. ENH tries to detect such problems by
building a method call closure and propagating thrown exceptions.
ENH considers only exceptions explicitly generated by a program (using the
throw
statement) and not runtime exceptions caused by system methods, such as
invalid array index or null reference exceptions.
Unfortunately, it is not clear when an exception has to be caught and handled,
so error messages are produced by ENH in two situations:
try-catch
statement (so the
try-catch
statement handles some other exception, but not this one).Incorrect:
class Database {
public void Open(string fileName) {
if (!OpenFile(fileName)) {
throw new NoSuchFileException();
}
if (!ReadHeader()) {
throw new CorruptedFileException();
}
if (Version < SupportedVersion) {
throw new VersionNotSupportedException();
}
}
}
public class MyApplication {
public static void Main(string[] args) {
Database db = new Database();
try {
db.Open(args[0]);
} catch(NoSuchFileException x) {
DumpError("File not found");
}
}
}
Correct:
class Database {
public void Open(string fileName) {
if (!OpenFile(fileName)) {
throw new NoSuchFileException();
}
if (!ReadHeader()) {
throw new CorruptedFileException();
}
if (Version < SupportedVersion) {
throw new VersionNotSupportedException();
}
}
}
public class MyApplication {
public static void Main(string[] args) {
Database db = new Database();
try {
db.Open(args[0]);
} catch(NoSuchFileException x) {
DumpError("File not found");
} catch(CorruptedFileException x) {
DumpError("File is corrupted");
} catch(VersionNotSupportedException x) {
DumpError("Version is not supported");
}
}
}